﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using InfoJetSoft.Service.Entity;

//CID 0702 //2010.11.29 //Begin
namespace InfoJetSoft.Service.Util
{
    class SDSMonitor
    {
        private Form form = null;
        private Dictionary<XmlDocument, DataObject> sdsDataTable = null;
        private String newId = Guid.NewGuid().ToString();
        private int index = 0;

        public SDSMonitor(Form frm)
        {
            this.form = frm;
            this.sdsDataTable = new Dictionary<XmlDocument, DataObject>();

            foreach (DataObject dataObject in form.Manifest.DataObjectList)
            {
                foreach (View view in this.form.Manifest.ViewList)
                {
                    if (view.SDSInView.SDSList != null && view.SDSInView.SDSList.Contains(dataObject.Name))
                    {
                        XmlDocument dataDoc = form.DataTable[dataObject.Name] as XmlDocument;
                        //CID 1292 //2012.08.27 //Begin
                        if (dataDoc != null)
                        {
                            this.sdsDataTable[dataDoc] = dataObject;
                            dataDoc.NodeInserted += new XmlNodeChangedEventHandler(DataDoc_NodeInserted);
                        }
                        //CID 1292 //2012.08.27 //End
                        break;
                    }
                }
            }
        }

        public void Stop()
        {
            foreach (XmlDocument sdsDoc in this.sdsDataTable.Keys)
            {
                sdsDoc.NodeInserted -= new XmlNodeChangedEventHandler(DataDoc_NodeInserted);
            }
        }

        void DataDoc_NodeInserted(object sender, XmlNodeChangedEventArgs e)
        {
            if (e.Node is XmlElement)
            {
                XmlElement element = e.Node as XmlElement;
                XmlDocument sdsDoc = element.OwnerDocument;
                DataObject dataObject = this.sdsDataTable[sdsDoc];
                element.SetAttribute(JetConstant.JetId, "_s_" + dataObject.Id + "_" + this.newId + "_" + (this.index++));
            }
        }
    }
}
//CID 0702 //2010.11.29 //End